<template>
  <div class="scenic-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input 
            v-model="searchForm.name" 
            placeholder="搜索景区名称/地区/类型" 
            clearable
            @input="handleSearchInput"
            @clear="resetSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div v-if="filteredScenicList.length > 0" class="search-stats">
        找到 {{ filteredScenicList.length }} 个匹配的景区
      </div>
    </div>
    
    <div class="header">
      <el-button type="primary" @click="handleAdd">新增景区</el-button>
    </div>

    <el-table :data="scenicList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="景区名称" width="120" />
      <el-table-column prop="area" label="所在地区" width="120" />
      <el-table-column prop="type" label="景区类型" width="120" />
      <el-table-column prop="ticketPrice" label="门票价格" width="100">
        <template #default="scope">
          ¥{{ scope.row.ticketPrice }}
        </template>
      </el-table-column>
      <el-table-column prop="openTime" label="开放时间" width="120" />
      <el-table-column prop="view" label="浏览量" width="100" />
      <el-table-column prop="score" label="评分" width="100">
        <template #default="scope">
          <el-rate v-model="scope.row.score" disabled />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
      <el-form :model="form" label-width="120px">
        <el-form-item label="景区名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="所在地区">
          <el-input v-model="form.area" />
        </el-form-item>
        <el-form-item label="景区类型">
          <el-select v-model="form.type" placeholder="请选择景区类型" default-first-option>
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.typeName"
              :value="item.typeName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="form.addressDetail" />
        </el-form-item>
        <el-form-item label="景区图片">
          <el-upload
            v-model:file-list="fileList"
            action="/api/upload/image"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :headers="uploadHeaders"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="门票价格">
          <el-input-number v-model="form.ticketPrice" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="开放时间">
          <el-time-picker
            v-model="form.openTime"
            format="HH:mm"
            value-format="HH:mm"
            placeholder="选择开放时间"
          />
        </el-form-item>
        <el-form-item label="景区介绍">
          <el-input v-model="form.info" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="previewVisible">
      <img w-full :src="previewUrl" alt="Preview Image" />
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="景区详情" width="60%">
      <div v-if="detailData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="景区名称">{{ detailData.name }}</el-descriptions-item>
          <el-descriptions-item label="所在地区">{{ detailData.area }}</el-descriptions-item>
          <el-descriptions-item label="景区类型">{{ detailData.type }}</el-descriptions-item>
          <el-descriptions-item label="门票价格">¥{{ detailData.ticketPrice }}</el-descriptions-item>
          <el-descriptions-item label="开放时间">{{ detailData.openTime }}</el-descriptions-item>
          <el-descriptions-item label="浏览量">{{ detailData.view }}</el-descriptions-item>
          <el-descriptions-item label="详细地址" :span="2">{{ detailData.addressDetail }}</el-descriptions-item>
          <el-descriptions-item label="评分">
            <el-rate v-model="detailData.score" disabled />
          </el-descriptions-item>
          <el-descriptions-item label="景区介绍" :span="2">
            {{ detailData.info }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-images" v-if="detailData.imgUrl">
          <h3>景区图片</h3>
          <div class="image-list">
            <el-image 
              v-for="(url, index) in detailData.imgUrl.split(',')" 
              :key="index"
              :src="url"
              :preview-src-list="detailData.imgUrl.split(',')"
              fit="cover"
              style="width: 100px; height: 100px; margin: 5px;"
            />
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { scenicAPI } from '@/utils/api'

const scenicList = ref([])
const allScenicList = ref([]) // 存储所有景区数据
const filteredScenicList = ref([]) // 存储搜索筛选后的景区数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const previewVisible = ref(false)
const previewUrl = ref('')
const fileList = ref([])
const typeOptions = ref([])

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 详情数据
const detailVisible = ref(false)
const detailData = ref(null)

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const form = ref({
  name: '',
  area: '',
  type: '',
  addressDetail: '',
  imgUrl: '',
  ticketPrice: 0,
  openTime: '',
  info: ''
})

// 为搜索防抖设置一个延时器变量
const searchTimeout = ref(null)

// 获取景区列表数据
const getList = () => {
  console.log('正在获取景区列表，参数:', {
    pageNum: 1,
    pageSize: 1000
  });
  
  const params = {
    pageNum: 1,  // 请求所有数据，前端处理分页
    pageSize: 1000  // 设置一个较大的值以获取所有数据
  };
  
  // 调用接口前添加日志
  console.log('发起请求: GET /api/admin/scenic/list');
  
  return scenicAPI.getAll(params).then(res => {
    console.log('景区列表响应:', res);
    if(res.data.code === 200) {
      // 获取列表数据
      const responseData = res.data.data;
      
      // 检查响应数据格式，适配不同的后端响应结构
      if (Array.isArray(responseData)) {
        // 如果返回的是数组，直接使用
        allScenicList.value = responseData;
      } else if (responseData && typeof responseData === 'object') {
        // 尝试从不同格式的对象中提取数据
        if (responseData.list) {
          // {list: [...], total: 100} 格式
          allScenicList.value = responseData.list;
        } else if (responseData.records) {
          // MyBatis Plus 分页格式 {records: [...], total: 100}
          allScenicList.value = responseData.records;
        } else {
          // 其他格式，尽量适配
          const possibleList = Object.values(responseData).find(val => Array.isArray(val));
          if (possibleList) {
            allScenicList.value = possibleList;
          } else {
            allScenicList.value = [];
            console.error('无法识别的数据格式:', responseData);
          }
        }
      } else {
        // 如果数据格式完全无法识别
        allScenicList.value = [];
        console.error('无法识别的数据格式:', responseData);
      }
      
      // 如果有搜索条件，先过滤数据
      if (searchForm.name) {
        filterScenicList();
      } else {
        // 前端分页处理
        updateScenicList();
      }
      
      return res; // 返回响应以便链式调用
    } else {
      ElMessage.error(res.data.message || '获取景区列表失败');
      allScenicList.value = [];
      scenicList.value = [];
      total.value = 0;
      return Promise.reject(res.data.message || '获取景区列表失败');
    }
  }).catch(err => {
    console.error('获取景区列表失败:', err);
    ElMessage.error("数据加载失败!");
    allScenicList.value = [];
    scenicList.value = [];
    total.value = 0;
    return Promise.reject(err);
  });
}

// 前端模糊搜索过滤
const filterScenicList = () => {
  if (!searchForm.name || !allScenicList.value) {
    updateScenicList();
    return;
  }
  
  console.log(`正在执行前端模糊搜索，关键词: "${searchForm.name}"`);
  
  // 使用小写不区分大小写进行搜索
  const keyword = searchForm.name.toLowerCase();
  
  // 筛选包含搜索关键字的景区
  const filteredList = allScenicList.value.filter(item => {
    // 检查景区名称、地区、类型和详细地址是否包含关键字
    const nameMatch = item.name && item.name.toLowerCase().includes(keyword);
    const areaMatch = item.area && item.area.toLowerCase().includes(keyword);
    const typeMatch = item.type && item.type.toLowerCase().includes(keyword);
    const addrMatch = item.addressDetail && item.addressDetail.toLowerCase().includes(keyword);
    
    return nameMatch || areaMatch || typeMatch || addrMatch;
  });
  
  console.log(`搜索结果: 找到 ${filteredList.length} 个匹配项`);
  
  // 更新筛选后的列表
  filteredScenicList.value = filteredList;
  
  // 重置到第一页
  currentPage.value = 1;
  
  // 更新分页
  updateFilteredList();
}

// 更新筛选后的列表分页
const updateFilteredList = () => {
  // 确保数据存在
  if (!filteredScenicList.value || filteredScenicList.value.length === 0) {
    scenicList.value = [];
    total.value = 0;
    return;
  }

  // 设置总记录数
  total.value = filteredScenicList.value.length;
  
  // 如果当前页码超出范围，重置为第一页
  const maxPage = Math.ceil(total.value / pageSize.value) || 1;
  if (currentPage.value > maxPage) {
    currentPage.value = 1;
  }
  
  // 计算当前页的数据
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = Math.min(startIndex + pageSize.value, total.value);
  
  // 将当前页的数据赋值给 scenicList
  scenicList.value = filteredScenicList.value.slice(startIndex, endIndex);
  
  console.log(`前端分页（筛选后）：当前第${currentPage.value}页，每页${pageSize.value}条，总共${total.value}条`);
  console.log(`显示的数据范围：${startIndex} - ${endIndex - 1}`);
}

// 搜索景区 - 使用前端模糊搜索
const handleSearch = () => {
  console.log('执行搜索，关键词:', searchForm.name);
  currentPage.value = 1; // 重置到第一页
  
  if (searchForm.name) {
    filterScenicList();
  } else {
    filteredScenicList.value = []; // 清空筛选列表
    updateScenicList(); // 显示全部数据
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = '';
  currentPage.value = 1;
  filteredScenicList.value = []; // 清空筛选列表
  updateScenicList(); // 显示全部数据
}

// 更新当前页的景区列表 - 前端分页
const updateScenicList = () => {
  // 确保数据存在
  if (!allScenicList.value || allScenicList.value.length === 0) {
    scenicList.value = [];
    total.value = 0;
    return;
  }

  // 设置总记录数
  total.value = allScenicList.value.length;
  
  // 如果当前页码超出范围，重置为第一页
  const maxPage = Math.ceil(total.value / pageSize.value) || 1;
  if (currentPage.value > maxPage) {
    currentPage.value = 1;
  }
  
  // 计算当前页的数据
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = Math.min(startIndex + pageSize.value, total.value);
  
  // 将当前页的数据赋值给 scenicList
  scenicList.value = allScenicList.value.slice(startIndex, endIndex);
  
  console.log(`前端分页：当前第${currentPage.value}页，每页${pageSize.value}条，总共${total.value}条`);
  console.log(`显示的数据范围：${startIndex} - ${endIndex - 1}`);
}

// 处理页码变化
const handleCurrentChange = (page) => {
  console.log('页码变化:', page);
  currentPage.value = page;
  
  // 根据是否有搜索条件，使用不同的分页处理
  if (searchForm.name && filteredScenicList.value.length > 0) {
    updateFilteredList();
  } else {
    updateScenicList();
  }
}

// 处理每页显示数量变化
const handleSizeChange = (size) => {
  console.log('每页数量变化:', size);
  pageSize.value = size;
  currentPage.value = 1; // 重置到第一页
  
  // 根据是否有搜索条件，使用不同的分页处理
  if (searchForm.name && filteredScenicList.value.length > 0) {
    updateFilteredList();
  } else {
    updateScenicList();
  }
}

// 查看景区详情
const handleDetail = (row) => {
  scenicAPI.getDetail(row.id).then(res => {
    if(res.data.code === 200) {
      detailData.value = res.data.data;
      detailVisible.value = true;
    } else {
      ElMessage.error(res.data.message || '获取景区详情失败');
    }
  }).catch((err) => {
    console.error('获取景区详情失败:', err);
    ElMessage.error('获取景区详情失败');
  });
}

const handleAdd = () => {
  dialogTitle.value = '新增景区'
  dialogVisible.value = true
  form.value = {
    name: '',
    area: '',
    type: '',
    addressDetail: '',
    images: [],
    ticketPrice: 0,
    openTime: '',
    info: ''
  }
  fileList.value = []
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑景区'
  dialogVisible.value = true
  // 创建新对象，避免直接引用row
  const formData = {...row}
  
  // 确保时间格式正确
  if (typeof formData.openTime === 'string' && formData.openTime) {
    // 如果时间是字符串格式，确保它符合HH:mm格式
    if (!/^\d{2}:\d{2}$/.test(formData.openTime)) {
      formData.openTime = '09:00'; // 默认时间
    }
  } else {
    formData.openTime = '09:00'; // 默认时间
  }
  
  form.value = formData
  fileList.value = row.imgUrl ? row.imgUrl.split(',').map(url => ({
    url,
    name: url.substring(url.lastIndexOf('/') + 1)
  })) : []
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该景区吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用接口前添加日志
    console.log('发起删除请求: GET /api/admin/scenic/remove/' + id);
    
    // 保存当前搜索条件
    const currentSearchTerm = searchForm.name;
    
    scenicAPI.delete(id).then(res => {
      console.log('删除景区响应:', res);
      if(res.data.code === 200) {
        ElMessage.success('删除景区成功');
        
        // 重新获取数据
        getList().then(() => {
          // 恢复搜索
          if (currentSearchTerm) {
            searchForm.name = currentSearchTerm;
            filterScenicList();
          }
        });
      } else {
        ElMessage.error(res.data.message || '删除景区失败');
      }
    }).catch((err) => {
      console.error('删除景区失败:', err);
      ElMessage.error('删除景区失败');
    });
  }).catch(() => {});
}

const handlePictureCardPreview = (file) => {
  console.log('预览图片:', file);
  previewUrl.value = file.url
  previewVisible.value = true
}

const handleUploadSuccess = (response, file, fileList) => {
  console.log('图片上传成功响应:', response);
  console.log('当前上传文件:', file);
  console.log('当前文件列表:', fileList);
  
  if(response && response.code === 200) {
    // 提取所有文件URL
    const urls = fileList.map(file => {
      // 检查文件对象是否有完整的URL
      if (file.response && file.response.data) {
        return file.response.data;
      } else if (file.url) {
        return file.url;
      }
      return '';
    }).filter(url => url); // 过滤空URL
    
    // 设置表单中的图片URL字段
    form.value.imgUrl = urls.join(',');
    console.log('更新后的图片URL:', form.value.imgUrl);
  } else {
    console.error('图片上传响应异常:', response);
    ElMessage.error('图片上传失败');
  }
}

const handleUploadError = (error, file, fileList) => {
  console.error('图片上传失败:', error);
  console.log('上传失败的文件:', file);
  ElMessage.error('图片上传失败，请重试');
}

const handleSubmit = () => {
  if (!form.value.name || !form.value.area || !form.value.type) {
    ElMessage.warning('请填写必要的景区信息');
    return;
  }
  
  // 确保提交前时间格式正确
  if (!form.value.openTime) {
    form.value.openTime = '09:00';
  }
  
  // 根据是否有ID判断是新增还是更新
  const apiMethod = form.value.id ? scenicAPI.update : scenicAPI.add;
  
  // 保存当前搜索条件
  const currentSearchTerm = searchForm.name;
  
  // 无需区分ID传参了，现在都是传整个对象
  apiMethod(form.value).then(res => {
    console.log(`${form.value.id ? '更新' : '添加'}景区响应:`, res);
    if(res.data.code === 200) {
      ElMessage.success(form.value.id ? '更新景区成功' : '添加景区成功');
      dialogVisible.value = false;
      
      // 重新获取数据
      getList().then(() => {
        // 恢复搜索
        if (currentSearchTerm) {
          searchForm.name = currentSearchTerm;
          filterScenicList();
        }
      });
    } else {
      ElMessage.error(res.data.message || (form.value.id ? '更新景区失败' : '添加景区失败'));
    }
  }).catch((err) => {
    console.error(form.value.id ? '更新景区失败:' : '添加景区失败:', err);
    ElMessage.error(form.value.id ? '更新景区失败' : '添加景区失败');
  });
}

// 获取景区类型列表
const getScenicTypes = () => {
  // 调用接口前添加日志
  console.log('发起请求: GET /api/type/all');
  
  scenicAPI.getAllTypes().then(res => {
    console.log('景区类型响应:', res);
    if(res.data.code === 200) {
      typeOptions.value = res.data.data || [];
    }else{
      ElMessage.error(res.data.message || '获取景区类型失败');
    }
  }).catch(err => {
    console.error('获取景区类型失败:', err);
    ElMessage.error("类型数据加载失败!");
  });
}

// 设置上传请求头
const uploadHeaders = reactive({
  // 如果需要携带token等认证信息
  'Authorization': localStorage.getItem('token') || ''
})

// 处理实时搜索输入
const handleSearchInput = () => {
  // 使用防抖处理，避免频繁搜索
  clearTimeout(searchTimeout.value);
  searchTimeout.value = setTimeout(() => {
    if (searchForm.name) {
      filterScenicList();
    } else {
      resetSearch();
    }
  }, 300); // 300ms延迟
}

onMounted(() => {
  // 添加控制台消息
  console.log('景区管理页面已加载，准备获取数据');
  // 获取景区列表数据
  getList();
  // 获取景区类型
  getScenicTypes();
})
</script>

<style scoped>
.scenic-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-images {
  margin-top: 20px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}

.search-stats {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}
</style>